<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PasswordAccess
{
    public function handle(Request $request, \Closure $next)
    {
        $siteId = $this->checkSite($request);
        $passwordEnable = DB::table('setting')->where([
            'site' => $siteId,
            'type' => 'enablePasswordAccess',
            'value'=> "1"
        ])->exists();
        $password = $request->cookie('access_password');
        if ($passwordEnable) {
            if (!$password) {
                return view('Web.private_login', [
                    'msg' => ''
                ]);
            } else {
                $passwordInDb = DB::table('setting')->where([
                    'site' => $siteId,
                    'type' => 'accessPassword'
                ])->first();
                if ($passwordInDb->value != $password) {
                    return view('Web.private_login', [
                        'msg' => '请重新输入密码'
                    ]);
                }
            }
        }

        return $next($request);
    }

    public function checkSite(Request $request)
    {
        $host = $request->getHost();
        $port = $request->getPort();
        if ($port && $port != 80 && $port != 443) $host = "{$host}:{$port}";

        $hostFromDb = DB::table('site')->where([
            'is_del' => 0
        ])->where('host', 'like', "%,{$host},%")->first();
        // 后台管理系统不受此限制
        if (stripos($request->url(), 'admin') !== false) {
            if ($hostFromDb && $hostFromDb->id > 0) {
                return $hostFromDb->id;
            }
        } else {
            if (!$hostFromDb) {
                die('该站点不存在，请在管理后台配置');
            }
            if ($hostFromDb && $hostFromDb->id > 0) {
                return $hostFromDb->id;
            }
        }
    }
}
